package nl.ypmits.utils.as3.view.movieclip {
	import nl.ypmits.utils.as3.math.SimpleMath;

	import flash.display.*;
	import flash.events.*;

	public dynamic class ReversableMovieClip extends MovieClip 	{
		private var _speed : Number = 1;
		protected var _forward : Boolean = true;
		private var _currentFrame : Number = 1;
		public function ReversableMovieClip() 		{			_forward = true;
			_speed = 1;
			stop();
		}
		public function playBackward(speed : Number = 1) : void 		{
			_currentFrame = currentFrame;
			_speed = speed;
			_forward = false;
			addEventListener(Event.ENTER_FRAME, animate);
		}
		public function stopAnimation() : void 		{
			removeEventListener(Event.ENTER_FRAME, animate);
		}		override public function stop() : void		{			super.stop();			stopAnimation();
		}		protected function animate(event : Event) : void 		{
			if (_forward) 			{
				_currentFrame += _speed;
				gotoAndStop(Math.round(SimpleMath.setBounds(_currentFrame, 1, totalFrames)));
				if (currentFrame == totalFrames) 				{
					stopAnimation();
					dispatchEvent(new ReversableMovieClipEvent(ReversableMovieClipEvent.FORWARD_ANIMATION_DONE));
				}
			} 			else 			{
				_currentFrame -= _speed;
				gotoAndStop(Math.round(SimpleMath.setBounds(_currentFrame, 1, totalFrames)));
				if (currentFrame == 1) 				{
					stopAnimation();
					dispatchEvent(new ReversableMovieClipEvent(ReversableMovieClipEvent.BACKWARD_ANIMATION_DONE));
				}
			}
		}
		public function playForward(speed : Number = 1) : void 		{
			_currentFrame = currentFrame;
			_speed = speed;
			_forward = true;
			addEventListener(Event.ENTER_FRAME, animate);
		}
	}
}
